package com.flute.icrawler.app;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class YoukuCommentTool {

	public void extract(String ID, String videoUrls, String pathname) {

		File file = new File(pathname);
		File fileComment = new File("E://" + ID + ".comment");

		try {
			BufferedInputStream bufferedInputStream = new BufferedInputStream(
					new FileInputStream(file));
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			byte[] bs = new byte[4096];
			int len = -1;
			while (-1 != (len = bufferedInputStream.read(bs))) {
				byteArrayOutputStream.write(bs, 0, len);
			}

			byte[] contentBytes = byteArrayOutputStream.toByteArray();

			String[] commentsUrl = extractor(new String(contentBytes));

			if (!fileComment.exists()) {
				fileComment.createNewFile();
			}

			BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
					new FileOutputStream(fileComment));
			for (int i = 0; i < commentsUrl.length; i++) {
				bufferedOutputStream
						.write((commentsUrl[i] + "\r\n").getBytes());
			}
			bufferedOutputStream.flush();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public String[] extractor(String content) {

		// 填写视频ID 和时间戳
		String[] paras = { getVideoID(content), getTimeStr(content) };

		// 获得未取得分页信息的链接
		String commentNoPage = replaceParas(getCommentTemplate(), paras);

		int pages = getMaxPage(content);

		String[] comments = new String[pages];
		for (int i = 1; i <= pages; i++) {
			String[] paraPage = { "" + i };
			comments[i - 1] = replaceParas(commentNoPage, paraPage);
		}

		return comments;
	}

	public static String getCommentTemplate() {
		return "http://v.youku.com/v_vpcommentContent/id_#_time_#_page_#.html?__rt=1&__ro=videobodycommentlist";
	}

	/**
	 * 填写模板中需要的参数
	 * 
	 * @param originalURL
	 *            链接格式模板
	 * @param paras
	 *            链接中动态的参数
	 * @return
	 */
	private static String replaceParas(String originalURL, String[] paras) {

		for (int i = 0; i < paras.length; i++) {
			String para = paras[i];
			if (null == para) {
				break;
			}
			originalURL = originalURL.replaceFirst("#", paras[i]);
		}

		return originalURL;

	}

	private String getVideoID(String strContent) {

		String regEx = "var videoId2= '(.*)';";

		Pattern p = Pattern.compile(regEx);
		Matcher matcher = p.matcher(strContent);
		if (matcher.find()) {
			return matcher.group(1);
		}
		return "";

	}

	private String getTimeStr(String strContent) {
		String regEx = "//nova_update\\('videobodycommentlist'\\, '/v_vpcommentContent/id_'\\+videoId\\+'_time_(.*)'\\);";
		Pattern p = Pattern.compile(regEx);
		Matcher matcher = p.matcher(strContent);
		if (matcher.find()) {
			return matcher.group(1);
		}
		return "";

	}

	/**
	 * 获取可以出现的最大页数
	 * 
	 * @param strContent
	 * @return
	 */
	private static int getMaxPage(String strContent) {
		int page = 1;
		String regEx = "name=\"span_detailcommenttotal\">(\\d+)</span>";
		Pattern p = Pattern.compile(regEx);
		Matcher matcher = p.matcher(strContent);
		if (matcher.find()) {
			// 总的评论条数
			int totalComments = Integer.parseInt(matcher.group(1));
			// 每页显示30条
			page = totalComments / 30 + 1;

		}
		return page;
	}

	public static void main(String[] args) {

		YoukuCommentTool commentTool = new YoukuCommentTool();
		commentTool.extract("883157",
				"http://v.youku.com/v_show/id_XMjM4MTY4NTky.html",
				"f://id_XMjM4MTY4NTky.HTML");
	}
}
